/*
 ** name check 姓名校验
 **
 ** 校验规则：
 ** 1、字符类型；
 ** 2、除“ ”外不允许输入其他特殊字符；
 ** 3、长度为60位字符；
 **
 */

(function() {
	'use strict';

	angular
		.module('elife')
		.directive('autoCheck', autoCheck);

	autoCheck.$inject = ['AllUsersService', '$timeout', '$rootScope'];
	/** @ngInject */
	function autoCheck(AllUsersService, $timeout, $rootScope) {
		var directive = {
			restrict: 'A',
			require: 'ngModel',
			link: linkFunc,

		};

		return directive;

		function linkFunc(scope, elem, attr, ngModel) {
			var html;
			scope.$watch(attr.ngModel, function(newValue, oldValue) {
				if (newValue) {
					if (newValue == attr.sel) {
						$('.auto-check').remove();
					} else {
						scope.allUsers = AllUsersService.selectUsers(newValue, attr.name);
						if (scope.allUsers && scope.allUsers.length > 0) {
							$('.auto-check').remove();
							elem.after('<div id="auto" style="position: absolute;left:2px;width: 180px;;background-color: #fff;top:34px;border:2px solid #ebebeb;box-shadow:2px 2px 5px #ebebeb;" class="auto-check"><ul></ul></div>');
							$('ul').children('li').remove();
							// 将html全部解析再渲染进来
							for (var i = 0; i < scope.allUsers.length; i++) {
								var user = scope.allUsers[i];
								html = ('<li style="border-bottom:1px solid #ebebeb;height:34px;padding:5px">' + user[attr.name] + '</li>');
								$('ul').append(html);
							}
							//给每个li加上监听，判断哪个客户信息被选中
							var $li = $('li');
							if ($li && $li.length > 0) {
								for (var i = 0; i < $li.length; i++) {
									$li[i].setAttribute('i', i);
									$li[i].onclick = function() {
										var index = this.getAttribute('i');
										// 将所选客户返回
										$rootScope.$broadcast('send-result', {
											result: scope.allUsers[index]
										});
										$timeout(function() {
											$('.auto-check').remove();
										}, 1); // 关于选中之后列表框的消失有问题
									}
								}
							}

						} else {
							$('.auto-check').remove();
						}
					}
				} else {
					$rootScope.$broadcast('send-result', {
						result: {}
					});
					$('.auto-check').remove();
				}
			});
		}
	}
})();